import Vapor
import Fluent

struct UserController: RouteCollection {
    func boot(routes: RoutesBuilder) throws {
        let userRoute = routes.grouped("api", "users")
        userRoute.post(use: createHandler)
        userRoute.get(use: getAllHandler)
//        userRoute.get(":userID", use: getHandler)
        userRoute.get(":machineUniqueIdentification", use: getHandlerMachineUniqueIdentification)

        userRoute.put(use: updateHandler)
        userRoute.delete(use: deleteHandler)

    }
    
    func createHandler(_ req: Request) throws -> EventLoopFuture<User>  {
        let user = try req.content.decode(User.self)
        return user.save(on: req.db).map { user }
    }
    
    func getAllHandler(_ req: Request) throws -> EventLoopFuture<[User]> {
        User.query(on:req.db).all()
    }
    
//    func getHandler(_ req: Request) throws -> EventLoopFuture<User> {
//        User.find(req.parameters.get("userID"), on: req.db).unwrap(or: Abort(.notFound))
//    }
    
    func getHandlerMachineUniqueIdentification(_ req: Request) throws -> EventLoopFuture<User> {
        let machineUniqueIdentification = req.parameters.get("machineUniqueIdentification")!
        let uuid = "\(machineUniqueIdentification)"
        
        return User.query(on: req.db).filter(\.$machineUniqueIdentification == uuid).first().unwrap(or: Abort(.notFound))
    }
    
    func updateHandler(_ req: Request) throws -> EventLoopFuture<User> {
        let data = try req.content.decode(User.self)
        return User.find(data.id, on: req.db).unwrap(or: Abort(.notFound)).flatMap { user in
            user.abbreviation = data.abbreviation
            user.firstName = data.firstName
            user.lastName = data.lastName
            user.machineUniqueIdentification = data.machineUniqueIdentification
            user.email = data.email
            user.nextcloudPassword = data.nextcloudPassword
            user.telephone = data.telephone
            user.isMale = data.isMale
            user.isBlocked = data.isBlocked
            user.isAllowedToChangeImages = data.isAllowedToChangeImages
            user.isAllowedToChangeReferences = data.isAllowedToChangeReferences
            user.isAllowedToSendMessage = data.isAllowedToSendMessage
            user.isAllowedToChangePDFs = data.isAllowedToChangePDFs
            user.isAllowedToChangeVideos = data.isAllowedToChangeVideos
            user.licenseExpire = data.licenseExpire
            return user.save(on: req.db).map { return user }

        }
    }
    
    func deleteHandler(_ req: Request) throws -> EventLoopFuture<HTTPStatus> {
        let data = try req.content.decode(User.self)
        
        return User.find(data.id, on: req.db).unwrap(or: Abort(.notFound)).flatMap { user in
            user.delete(on: req.db).transform(to: .noContent)
        }

    }
    

}


